package com.hspedu.furns.service.impl;

import com.hspedu.furns.dao.FurnDAO;
import com.hspedu.furns.dao.OrderDAO;
import com.hspedu.furns.dao.OrderItemDAO;
import com.hspedu.furns.dao.impl.FurnDAOImpl;
import com.hspedu.furns.dao.impl.OrderDAOImpl;
import com.hspedu.furns.dao.impl.OrderItemDAOImpl;
import com.hspedu.furns.entity.*;
import com.hspedu.furns.service.OrderService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class OrderServiceImpl implements OrderService {

    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();


    @Override
    public String saveOrder(Cart cart, int memberId) {

        //先生成一个UUID, 表示当前的订单号, 订单号要保证是唯一
        String orderId = System.currentTimeMillis() + "" + memberId;
        Order order =
                new Order(orderId, new Date(), cart.getCartTotalPrice(), 0, memberId);
        //保存order到数据表.
        orderDAO.saveOrder(order);


        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            CartItem item = entry.getValue();
            //通过cartItem对象构建了OrderItem
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(),
                    item.getCount(), item.getTotalPrice(), orderId);

            //保存
            orderItemDAO.saveOrderItem(orderItem);

            //更新一把furn表的sales销量, stock存量
            //(1) 获取到furn对象
            Furn furn = furnDAO.queryFurnById(item.getId());
            //(2) 更新一下这个furn的sales销量, stock存量
            furn.setSales(furn.getSales() + item.getCount());
            furn.setStock(furn.getStock() - item.getCount());
            //(3) 更新到数据表
            furnDAO.updateFurn(furn);

        }

        //清空购物车
        cart.clear();
        return orderId;
    }
}
